package com.indusfo.spc.service.impl;

import com.indusfo.spc.exception.GlobalException;
import com.indusfo.spc.exception.ParamsErrorException;
import com.indusfo.spc.exception.QueryFailedException;
import com.indusfo.spc.mapper.DepMapper;
import com.indusfo.spc.mapper.MenuMapper;
import com.indusfo.spc.mapper.RoleMenuMapper;
import com.indusfo.spc.mapper.UserMapper;
import com.indusfo.spc.pojo.Menu;
import com.indusfo.spc.pojo.Role;
import com.indusfo.spc.pojo.RoleMenu;
import com.indusfo.spc.pojo.User;
import com.indusfo.spc.service.UserService;
import com.indusfo.spc.vo.JSONObject;
import com.indusfo.spc.vo.XCommonUtil;
import com.indusfo.spc.vo.XTreeNode;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 用户信息业务层实现类
 *
 * @author xiet 2018年11月23日 下午2:41:59
 */
@Service
public class UserServiceImpl implements UserService {

  private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
  private static final Integer REMARK_LENGTH = 50;
  private static final Integer USERCODE_LENGTH = 100;
  private static final String USERCODE = "admin";
  /**
   * 注入mapper
   */
  @Resource
  private UserMapper userMapper;
  @Resource
  private DepMapper depMapper;
  @Resource
  private MenuMapper menuMapper;

  @Resource
  private RoleMenuMapper roleMenuMapper;

  /**
   * 删除用户信息（1启用，2删除，3停用）
   */
  @Override
  public JSONObject deleteUser(Integer[] userIds, Integer dataState) {
    try {
      //判断拆入id是否为1，超级用户不允许被删除
      for (Integer userId : userIds) {
        if (userId == 1) {
          throw new ParamsErrorException("admin用户不允许修改");
        }
      }
      // 判断传入的数据状态是否为空
      if (dataState == null) {
        // 如果为空，抛出异常
        throw new ParamsErrorException("数据状态不能为空");
      } else if (dataState != 1 && dataState != 2 && dataState != 3) {
        // 传入的数据状态不为1，2，3 抛出错误异常
        throw new ParamsErrorException("数据状态错误");
      }

      // 判断出入的用户id是否为空
      if (userIds == null) {
        // 如果为空，抛出异常信息
        throw new ParamsErrorException("用户id不能为空");
      }
      int row = userMapper.deleteUser(userIds, dataState);
      String msg = "";
      if (row != 0) {
        // 判断传入的数据状态参数lDataState,返回相应信息
        switch (dataState) {
          case 1:
            msg = "启用成功";
            break;
          case 2:
            msg = "删除成功";
            break;
          case 3:
            msg = "停用成功";
            break;
          default:
            break;
        }
      }
      return JSONObject.oK(msg);
    } catch (GlobalException e) {//捕获自定义异常
      logger.error(e.getMessage());
      return JSONObject.build(JSONObject.ERROR, e.getMessage());
    }
  }

  /**
   * 查询用户
   */
  @Override
  public JSONObject queryUser(User user) {
    //声明listUser集合，用来装查询出来的参数
    List<User> listUser = null;
    try {
      Integer pagesize = user.getPagesize();
      Integer pageindex = user.getPageindex();
      if (pagesize != null && pageindex != null) {
        user.setIncept(pagesize * (pageindex - 1));
      }
      //获取用户id
      Integer userId = user.getUserId();
      //判断lUserId 是否存在，存在则是查询单个用户
      if (userId != null) {
        listUser = userMapper.getUser(userId);
      } else {
        //userId 不存在，则查询所有用户
        listUser = userMapper.listUser(user);
      }
      //判断查询出来的集合是否为空
      if (listUser.isEmpty()) {
        return JSONObject.oK("没有用户相关数据", listUser, 0);
      }
      //用来记录查询出来的条数
      int count = userMapper.countUser(user);
      return JSONObject.oK("查询成功", listUser, count);
    } catch (GlobalException e) {//捕获自定义异常
      logger.error(e.getMessage());
      return JSONObject.build(JSONObject.ERROR, e.getMessage());
    }
  }

  /**
   * 查询用户
   */
  /**
   * wangqi
   * <p>
   * 添加查询子部门下所有用户
   * 19/9/9   9:10
   *
   * @param user
   * @return
   */
  @Override
  public JSONObject queryUserDep(User user) {
    //声明listUser集合，用来装查询出来的参数
    List<User> listUser = null;
    try {
      Integer pagesize = user.getPagesize();
      Integer pageindex = user.getPageindex();
      if (pagesize != null && pageindex != null) {
        user.setIncept(pagesize * (pageindex - 1));
      }
      List<Integer>  depIdArr = new ArrayList<>();
      if(null == user.getDepId() || user.getDepId() == 0){
        depIdArr =depMapper.queryChild(null);
      }else{
        /*
        递归查询子集包含自己
          */
        depIdArr = depMapper.recursionIds(user.getDepId());
        depIdArr.add(user.getDepId());
      }
      user.setDepIdArr(depIdArr);
      listUser = userMapper.queryUserByDepId(user);
      //判断查询出来的集合是否为空
      if (listUser.isEmpty()) {
        return JSONObject.oK("没有用户相关数据", listUser, 0);
      }
      //用来记录查询出来的条数
      int count = userMapper.countUserByDepId(user);
      return JSONObject.oK("查询成功", listUser, count);
    } catch (GlobalException e) {//捕获自定义异常
      logger.error(e.getMessage());
      return JSONObject.build(JSONObject.ERROR, e.getMessage());
    }
  }


  /**
   * 新增用户信息
   */
  @Override
  public JSONObject insertUser(User user) {
    //判断基础信息是否符合数据库要求
    if (user.getRemark() == null) {
      user.setRemark("");
    }
    try {
      // 参数校验
      checkParam(user);
      //调用新增用户信息接口

      int row = userMapper.insertUser(user);
      int userId = user.getUserId();
      if (row == 0) {
        throw new QueryFailedException("新增用户信息失败");
      }
      return JSONObject.build(JSONObject.SUCCESS, "新增数据成功", userId);
    } catch (GlobalException e) {//捕获自定义异常
      logger.error(e.getMessage());
      return JSONObject.build(JSONObject.ERROR, e.getMessage());
    }
  }

  @Override
  public JSONObject loginUser(User user) {
    if (StringUtils.isEmpty(user.getUserCode())) {
      return JSONObject.build(403, "用户名不能为空");
    }
    if (StringUtils.isEmpty(user.getUserPwd())) {
      return JSONObject.build(403, "密码不能为空");
    }
    User userLogin;
    Map<String, Object> map = new HashMap<>();
    try {
      List<User> userInfo = userMapper.lU(user);

      if (userInfo == null || userInfo.size() == 0) {
        throw new QueryFailedException("账号不存在|密码错误");
      }
      String salt = userInfo.get(0).getSalt();
      String encryptPassword = encryptPassword(user.getUserCode(), user.getUserPwd(),salt);
      if (!encryptPassword.equals(userInfo.get(0).getUserPwd())) {
        throw new QueryFailedException("账号不存在|密码错误");
      }
      userLogin = userInfo.get(0);
      User userXO = new User();
      userXO.setUserId(userLogin.getUserId());
      userXO.setUserName(userLogin.getUserName());
      userXO.setUserCode(userLogin.getUserCode());
      userXO.setRoleId(userLogin.getRoleId());
      userXO.setRoleName(userLogin.getRoleName());
      userXO.setDepName(userLogin.getDepName());
      if (userXO.getUserId() == 1) {
        userXO.setAccess("super_admin");
      } else {
        if (userXO.getRoleName() == null) {
          userXO.setAccess("tourists");
        } else {
          if (userXO.getRoleName().contains("管理员")) {
            userXO.setAccess("admin");
          } else {
            userXO.setAccess("user");
          }
        }
      }
      map.put("user", userXO);
    } catch (GlobalException e) {
      return JSONObject.build(403, e.getMessage());
    }
    return JSONObject.oK("登陆成功", map, 1);
  }

  @Override
  public JSONObject treeMenu(Integer userId) {
    try {

      List<XTreeNode> tree = null;

      tree = new ArrayList<>();
      List<XTreeNode> nodes = new ArrayList<>();
      List<Menu> list;
      if (userId == 1) {
        list = menuMapper.selectMenuAll();
      } else {
        list = menuMapper.slectMenuByUserId(userId);
      }


      if (null != list) {
        for (Menu _MouldType : list) {
          XTreeNode node = new XTreeNode();
          node.setId(_MouldType.getMenuId());
          node.setpId(_MouldType.getMenuPid()==1 ? null : _MouldType.getMenuPid());
          node.setOpen(true);
          node.setTitle(_MouldType.getMenuName());
          nodes.add(node);
        }
      }
      tree = XCommonUtil.getTree(nodes, null);


      return JSONObject.oK("查询成功", tree, 1);
    } catch (GlobalException e) {//捕获自定义异常
      logger.error(e.getMessage());
      return JSONObject.build(JSONObject.ERROR, e.getMessage());
    }
  }

  @Override
  public JSONObject arrayMenu(Integer userId) {
    try {
      List<Menu> menulist;
      if (userId == 1) {
        menulist = menuMapper.selectMenuAll();
      } else {
        menulist = menuMapper.slectMenuByUserId(userId);
      }
      /*
      提取menu的menuCode集合
        */
      List<String> menuCodeList = menulist.stream().map(Menu::getMenuCode).collect(Collectors.toList());
      return JSONObject.oK("查询成功", menuCodeList, menulist.size());
      /*
      捕获自定义异常
       */
    } catch (GlobalException e) {
      logger.error(e.getMessage());
      return JSONObject.build(JSONObject.ERROR, e.getMessage());
    }
  }

  @Override
  public JSONObject listMenu(Integer userId) {
    try {
      List<Menu> menulist;
      if (userId == 1) {
        menulist = menuMapper.selectMenuAll();
      } else {
        menulist = menuMapper.slectMenuByUserId(userId);
      }

      return JSONObject.oK("查询成功", menulist, menulist.size());


    } catch (GlobalException e) {//捕获自定义异常
      logger.error(e.getMessage());
      return JSONObject.build(JSONObject.ERROR, e.getMessage());
    }
  }


  @Override
  public JSONObject arrayRole(Integer roleId) {
    try {

      List<RoleMenu> RoleMenuList = roleMenuMapper.selectByRoleId(roleId);
      List<String> strings = RoleMenuList.stream().map(RoleMenu::getMenuCode).collect(Collectors.toList());
      return JSONObject.oK("查询成功", strings, RoleMenuList.size());


    } catch (GlobalException e) {//捕获自定义异常
      logger.error(e.getMessage());
      return JSONObject.build(JSONObject.ERROR, e.getMessage());
    }
  }

  @Override
  public JSONObject listRole(Integer roleId) {
    try {

      List<RoleMenu> roleRightList = roleMenuMapper.selectByRoleId(roleId);

      return JSONObject.oK("查询成功", roleRightList, roleRightList.size());


    } catch (GlobalException e) {//捕获自定义异常
      logger.error(e.getMessage());
      return JSONObject.build(JSONObject.ERROR, e.getMessage());
    }
  }

  /**
   * 修改用户信息
   * <p>
   * wangqi
   * <p>
   * 新增用户编码不允许更改判断
   * <p>
   * 19/9/4  16:34
   */
  @Override
  public JSONObject updateUser(User user) {
    try {
      //判断用户编码是否为admin,admin用户不允许被修改
      if ((USERCODE).equals(user.getUserCode())) {
        throw new ParamsErrorException("超级用户admin不允许被修改信息");
      }
      //判断用户编码是否更改
      int num = userMapper.judgeUserCode(user);
      if (num == 0) {
        throw new ParamsErrorException("用户编码不允许更改");
      }
      // 参数校验
      checkParam(user);
      //调用修改的接口
      int row = userMapper.updateByPrimaryKeySelective(user);
      if (row == 0) {
        throw new QueryFailedException("更新用户信息失败");
      }
      return JSONObject.oK("编辑成功");
    } catch (GlobalException e) {//捕获自定义异常
      logger.error(e.getMessage());
      return JSONObject.build(JSONObject.ERROR, e.getMessage());
    }
  }

  /**
   * 根据用户名查询用户
   */
  @Override
  public List<User> queryU(User user) {
    //声明listU集合，用来装通过用户名查询出来的用户
    List<User> listU = null;
    //调用接口通过用户名查询用户
    listU = userMapper.lU(user);
    //判断集合是否为空
    if (listU.isEmpty()) {
      throw new QueryFailedException("没有相关数据");
    }
    return listU;
  }


  /**
   * 参数校验
   *
   * @param user
   */
  private void checkParam(User user) {
    //查询所有用户的用户编码
    String remark = user.getRemark();
    if (remark == null) {
      remark = "";
    }
    //判断传入的参数是否符合规定长度
    if ((USERCODE).equals(user.getUserCode())) {
      throw new ParamsErrorException("admin为超级用户，只允许存在一个");
    }
    if (StringUtils.isBlank(user.getUserCode())) {
      throw new ParamsErrorException("用户编码不能为空");
    }
    if( null == user.getUserId()){
      if (StringUtils.isBlank(user.getUserPwd())) {
        throw new ParamsErrorException("用户密码不能为空");
      }
    }

    if (null == user.getDepId() || user.getDepId()<1) {
      throw new ParamsErrorException("请选择所属部门");
    }
    if (user.getUserCode().getBytes().length > REMARK_LENGTH) {
      throw new ParamsErrorException("用户编码长度过长");
    }
    if (remark.getBytes().length > USERCODE_LENGTH) {
      throw new ParamsErrorException("说明长度过长");
    }
    //判断用户编码是否存在
    int num = userMapper.listUserCode(user);
    if (num != 0) {
      throw new ParamsErrorException("用户编码已存在");
    }
    if (user.getDataState() == null) {
      user.setDataState(1);
    }
  }


  @Override
  public JSONObject insertListUser(List<User> userList) {
    int flag = userMapper.insertListUser(userList);
    if (flag > 0) {
      JSONObject.oK("新增成功");
    }
    return JSONObject.oK("新增失败");
  }

  @Override
  public String encryptPassword(String userCode, String password, String salt) {
    return new Md5Hash(userCode + password + salt).toHex().toString();
  }

  /**
   * 重置密码
   *
   * @param user
   */
  @Override
  public JSONObject resetPwd(User user) {
    try{
      if (StringUtils.isEmpty(user.getUserPwd())){
        throw new ParamsErrorException("重置密码不能为空");
      }
      int row = userMapper.updateByPrimaryKeySelective(user);
      if (row == 0) {
        throw new QueryFailedException("重置密码失败");
      }
      return JSONObject.oK("编辑成功");
    } catch (GlobalException e) {//捕获自定义异常
      logger.error(e.getMessage());
      return JSONObject.build(JSONObject.ERROR, e.getMessage());
    }
  }

  @Override
  public User selectUserBycode(String uesrCode) {
    return userMapper.selectUserBycode(uesrCode);
  }

  @Override
  public JSONObject selectByRole(Role role) {
    //声明listUser集合，用来装查询出来的参数
    List<User> listUser = null;
    try {
      Integer pagesize = role.getPagesize();
      Integer pageindex = role.getPageindex();
      if (pagesize != null && pageindex != null) {
        role.setIncept(pagesize * (pageindex - 1));
      }
      listUser = userMapper.selectByRole(role);
      //判断查询出来的集合是否为空
      if (listUser.isEmpty()) {
        return JSONObject.oK("没有用户相关数据", listUser, 0);
      }
      //用来记录查询出来的条数
      int count = userMapper.countUserByRole(role);
      return JSONObject.oK("查询成功", listUser, count);
    } catch (GlobalException e) {//捕获自定义异常
      logger.error(e.getMessage());
      return JSONObject.build(JSONObject.ERROR, e.getMessage());
    }
  }

  @Override
  public List<User> getUserCode(String userCode) {
    User user = new User();
    user.setUserCode(userCode);
    return  userMapper.lU(user);
  }

  @Override
  public User findUserById(Integer userId) {
    return userMapper.findUserById(userId);
  }


}
